import dayjs from "dayjs";
import { TaskProps } from "../types";

export const getTasksRange = (
  tasks: TaskProps[]
): [dayjs.Dayjs, dayjs.Dayjs] => {
  let newStartDate: dayjs.Dayjs = tasks[0].startDate;
  let newEndDate: dayjs.Dayjs = tasks[0].endDate;
  for (const task of tasks) {
    if (task.startDate < newStartDate) {
      newStartDate = task.startDate;
    }
    if (task.endDate > newEndDate) {
      newEndDate = task.endDate;
    }
  }
  return [
    newStartDate.subtract(1, "week").startOf("week"),
    newEndDate.add(1, "week").endOf("week"),
  ];
};

export const getDatesInRange = (start: dayjs.Dayjs, end: dayjs.Dayjs) => {
  let current = start;
  const dates = [];
  while (current.isBefore(end)) {
    dates.push(current);
    current = current.add(1, "day");
  }
  return dates;
};

export const getDaysInRange = (start: dayjs.Dayjs, end: dayjs.Dayjs) => {
  return end.diff(start, "day") + 1;
};

export const getMonthsInRange = (start: dayjs.Dayjs, end: dayjs.Dayjs) => {
  let current = start;
  const dates: Record<string, number> = {};
  while (current.isBefore(end)) {
    const month = current.format("YYYYMM");
    dates[month] = (dates[month] || 0) + 1;
    current = current.add(1, "day");
  }
  return dates;
};
